﻿package hapi.web;

class PathMatcherComposite implements PathMatcher {
	
	var elements:List<PathMatcher>;
	static inline var SEPARATOR = "/";
	
	public function new(path:String, factory:PathMatcherFactory) {
		var parts = path.split(SEPARATOR);
		elements = new List<PathMatcher>();
		for ( part in parts ) {
			elements.add( factory.create(part));
		}
	}
	
	public function match(uri:String, paramsToFill: { } ):Bool {
		if (StringTools.endsWith(uri, "/") && uri != "/")	uri = uri.substr(0, uri.length - 1);
		var uriParts = uri.split(SEPARATOR);
		var it = elements.iterator();
		if (uriParts.length != elements.length) return false;
		for ( part in uriParts ) {
			var element = it.next();
			if (!element.match(part,paramsToFill)) {
				return false;
			}
		}
		return true;
	}
	
	public function resolve(params:{}):String {
		var buf = new StringBuf();
		var it = elements.iterator();
		while (it.hasNext()) {
			var e = it.next();
			buf.add(e.resolve(params)+ (it.hasNext() ? SEPARATOR : ""));
		}
		return buf.toString();
	}
	
	public function paramsMatch(params:{}) {
		for (e in elements) {
			if (! e.paramsMatch(params)) return false;
		}
		return true;
	}
}